package com.ctsi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.system.constant.DictConstant;
import com.ctsi.system.entity.EmpExtOrgPos;
import com.ctsi.system.entity.Org;
import com.ctsi.system.entity.Pos;
import com.ctsi.system.mapper.EmpExtOrgPosMapper;
import com.ctsi.system.service.IEmpExtOrgPosService;
import com.ctsi.system.service.IOrgService;
import com.ctsi.system.service.IPosService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 员工附属机构岗位表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
@AllArgsConstructor
public class EmpExtOrgPosServiceImpl extends ServiceImpl<EmpExtOrgPosMapper, EmpExtOrgPos> implements IEmpExtOrgPosService {

	private final IOrgService orgService;
	private final IPosService posService;

	@Override
	public IPage<EmpExtOrgPos> listPage(Page page, Search search) {
		LambdaQueryWrapper<EmpExtOrgPos> queryWrapper = new LambdaQueryWrapper<>();
		return this.baseMapper.selectPage(page, queryWrapper);
	}

	@Override
	public List<Dict> getEmpExtOrgPosDictList(Long empId, boolean isFillId) {
		List<Dict> dictList = CollectionUtil.newArrayList();

		this.list(Wrappers.<EmpExtOrgPos>lambdaQuery()
				.eq(EmpExtOrgPos::getEmpId, empId))
				.forEach(empExtOrgPos -> {
					Dict dict = Dict.create();
					Long orgId = empExtOrgPos.getOrgId();
					Org org = orgService.getById(orgId);
					dict.put(DictConstant.EXT_ORG_CODE_DICT_KEY, org.getCode());
					dict.put(DictConstant.EXT_ORG_NAME_DICT_KEY, org.getName());

					Long posId = empExtOrgPos.getPosId();
					Pos pos = posService.getById(posId);
					dict.put(DictConstant.EXT_POS_CODE_DICT_KEY, pos.getCode());
					dict.put(DictConstant.EXT_POS_NAME_DICT_KEY, pos.getName());

					if (isFillId) {
						dict.put(DictConstant.EXT_ORG_ID_DICT_KEY, orgId);
						dict.put(DictConstant.EXT_POS_ID_DICT_KEY, posId);
					}
					dictList.add(dict);
				});
		return dictList;
	}

	@Override
	public boolean setExtOrgPos(Long empId, List<Dict> extIds) {
		// 删除职位附属信息，根据empId
		this.remove(Wrappers.<EmpExtOrgPos>query().lambda().eq(EmpExtOrgPos::getEmpId, empId));
		//　重新添加附属信息
		extIds.forEach(dict -> {
			Long orgId = dict.getLong(DictConstant.EXT_ORG_ID_DICT_KEY);
			Long posId = dict.getLong(DictConstant.EXT_POS_ID_DICT_KEY);
			EmpExtOrgPos empExtOrgPos = new EmpExtOrgPos();
			empExtOrgPos.setEmpId(empId);
			empExtOrgPos.setPosId(posId);
			empExtOrgPos.setOrgId(orgId);
			this.save(empExtOrgPos);
		});
		return Boolean.TRUE;
	}
}
